<script setup>
import { onUnmounted, ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import lodash from 'lodash';
import { SYSTEM_MENU_SORT_PRIORITIES } from '@/common/js/common-const';
import { useSystemStore } from '@/stores';
import { getToken } from '@/utils/auth';

const router = useRouter();

let intervalId;

const systemStore = useSystemStore();
const menuList = ref([]);
const menuItemChecked = ref();
const menuListIndex = ref({});
const menuTabChecked = ref();

const flag = ref(false);

const circleStyles = ref(Array(menuListIndex.value?.length).fill({}));

const roles = computed(() => systemStore.roles);
const launchMenus = computed(() => systemStore.launchMenus);

// 初始化卡片的位置
const initialPositions = [
  { transform: 'translateX(20rem) translateY(11rem)' }, //视频监控
  { transform: 'translateX(41rem) translateY(14rem)' }, //防火管控
  { transform: 'translateX(62rem) translateY(11rem)' }, //飞控平台
  { transform: 'translateX(79rem) translateY(1rem)' }, //物种多样性
  { transform: 'translateX(91rem) translateY(-13rem)' }, //科研监测
  { transform: 'translateX(81rem) translateY(-28rem)' }, //系统设置
  { transform: 'translateX(-4rem) translateY(-28rem)' }, //数据大屏
  { transform: 'translateX(-10rem) translateY(-13rem)' }, //资源管理
  { transform: 'translateX(1rem) translateY(1rem)' }, //护林巡护
];

circleStyles.value = [...initialPositions];

watch(
  [launchMenus, roles],
  () => {
    hasPermission();
  },
  { deep: true },
);

onMounted(async () => {
  await hasPermission();
});

onMounted(() => {
  // 先检查是否已经有数据
  if (systemStore.launchMenus.length > 0) {
    hasPermission();
  } else {
    // 否则监听变化
    const stopWatch = watch(
      () => systemStore.launchMenus,
      (newVal) => {
        if (newVal.length > 0) {
          hasPermission();
          stopWatch(); // 执行一次后解绑
        }
      },
      { immediate: true },
    );
  }
});

// 权限处理
const hasPermission = async () => {
  const promises = launchMenus?.value.map((item) => {
    if (systemStore?.businessMap[item.menuTitle]) {
      let _item = lodash.cloneDeep(item);

      return handlePermission(_item); // 这里可以不用 await，因为 Promise.all 会处理
    }

    return undefined;
  });
  // 等待所有 Promise 完成
  const results = await Promise.all(promises);

  // 过滤掉 undefined
  menuList.value = results.filter((value) => value !== undefined);

  // menuTabChecked.value = menuList?.value[0];
  menuItemChecked.value = menuList?.value[0]?.menuTabItems?.length
    ? menuList?.value[0]?.menuTabItems[0]
    : menuList?.value[0];
  flag.value = true;

  let originalMenu = separateByIndex(menuList.value);

  // 定义排序优先级

  const orderPriority = SYSTEM_MENU_SORT_PRIORITIES;

  // 创建 map 映射 menuTitle 到排序权重
  const priorityMap = {};

  orderPriority.forEach((title, index) => {
    priorityMap[title] = index;
  });

  // 排序
  menuListIndex.value = [...originalMenu].sort((a, b) => {
    return (priorityMap[a.menuTitle] || Infinity) - (priorityMap[b.menuTitle] || Infinity);
  });

  // intervalId = setInterval(updatePositions, 3000);
};

// 递归处理权限
const handlePermission = (menu) => {
  if (menu.menuItems) {
    menu.menuItems = menu.menuItems.map((item) => {
      if (systemStore?.businessMap[item.menuTitle]) {
        handlePermission(item);

        return item;
      }
    }); // 递归处理子菜单
    menu.menuItems = menu.menuItems.filter((value) => value !== undefined); // 过滤掉没有权限的子菜单
  }

  if (menu.menuTabItems) {
    menu.menuTabItems = menu.menuTabItems.map((item) => {
      if (systemStore?.businessMap[item.menuTitle]) {
        handlePermission(item);

        return item;
      }
    }); // 递归处理子菜单
    menu.menuTabItems = menu.menuTabItems.filter((value) => value !== undefined); // 过滤掉没有权限的子菜单
  }

  return menu;
};

const separateByIndex = (arr) => {
  let evenIndexElements = []; //偶数
  let oddIndexElements = []; //基数

  for (let i = 0; i < arr.length; i++) {
    if (i % 2 === 0) {
      evenIndexElements.push(arr[i]);
    } else {
      oddIndexElements.push(arr[i]);
    }
  }

  return [...evenIndexElements, ...oddIndexElements];
};

const handleMenu = (item) => {
  flag.value = false;

  menuTabChecked.value = item;

  if (item?.menuPath === '') {
    if (item?.menuTabItems?.length) {
      menuItemChecked.value = item?.menuTabItems[0];
    } else {
      menuItemChecked.value = item;
    }
  } else {
    if (item?.route == '外部') {
      const token = `${getToken()}`;

      // 目标页面 URL，将 token 作为查询参数传递
      const url = `http://219.147.125.119:8889/stLogin?ticket=${encodeURIComponent(token)}`;

      const a = document.createElement('a');

      a.href = url;
      a.target = '_blank';
      a.rel = 'noopener noreferrer';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } else {
      router.push({
        path: item?.menuPath,
        query: {
          code: item?.code,
        },
      });
    }
  }

  setTimeout(() => {
    flag.value = true;
  }, 100);
};

// 恢复旋转
const resumeRotation = () => {
  // intervalId = setInterval(updatePositions, 3000);
};

// 定时函数，用于更新卡片位置
// const updatePositions = () => {
//   const newPositions = [...circleStyles.value];

//   newPositions.push(newPositions.shift());
//   circleStyles.value = [...newPositions];
// };

onUnmounted(() => {
  clearInterval(intervalId);
});

// 暂停旋转
const pauseRotation = () => {
  clearInterval(intervalId);
};

const handleImageUrl = (url) => {
  return new URL(`../../assets/images/base-img/${url}.png`, import.meta.url).href;
};
</script>
<template>
  <div class="container">
    <div class="box">
      <div
        v-for="(item, index) in menuListIndex"
        :key="index"
        :class="['circle', `circle${index + 1}`]"
        :style="{
          ...circleStyles[index],
        }"
        class="flex-center flex-col"
        @mouseover="pauseRotation"
        @mouseout="resumeRotation"
        @click="handleMenu(item)"
      >
        <img
          :src="handleImageUrl(item.icon)"
          class="menu-icon relative z-20 mb-20px h-124px w-168px cursor-pointer"
          :class="menuTabChecked?.menuTitle === item?.menuTitle ? 'color-#ffffff' : 'color-#ABDCFF'"
        />

        <p class="headline flex-center pb-10px text-20px color-#fff">{{ item.menuTitle }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  // position: absolute;
  // top: 30%;
  // left: 50%;
  position: absolute;
  top: 55vh; // 视口高度的30%
  left: 50vw; // 水平居中
  z-index: 1;
  transform: translate(-50%, -50%);
}

.box {
  position: relative;
}

.circle {
  position: absolute;
  width: 236.3px;
  background-size: cover;
  cursor: pointer;
  transition: transform 1s ease;

  &:hover {
    p {
      // color: #46ccff;
      transform: scale(1.1);

      -webkit-animation: neon4 1.5s ease-in-out infinite alternate;
      -moz-animation: neon4 1.5s ease-in-out infinite alternate;
      animation: neon4 1.5s ease-in-out infinite alternate;
    }
  }

  .menu-icon {
    cursor: pointer;

    &:hover {
      transform: scale(1.2);
    }
  }
}

.headline {
  width: 190px;
  height: 48px;
  font-family: WDCH;
  background: url('@/assets/images/img/标题框.png') no-repeat center right;
  background-size: 100% 100%;
}
</style>
